package com.zidongxiangxi.lock.zookeeper;

import com.zidongxiangxi.lock.core.AbstractDistributedLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

/**
 * This is Description
 *
 * @author chenxudong
 * @date 2021/12/30
 */
public class ZookeeperDistributedLock extends AbstractDistributedLock {
    private final InterProcessMutex mutex;

    public ZookeeperDistributedLock(InterProcessMutex mutex) {
        this.mutex = mutex;
    }


    @Override
    public void lock() {
        try {
            mutex.acquire();
        } catch (Exception e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public void lockInterruptibly() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean tryLock() {
        try {
            return mutex.acquire(1, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            return false;
        } catch (Exception e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        try {
            return mutex.acquire(1, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public void unlock() {
        try {
            mutex.release();
        } catch (Exception e) {
            throw new IllegalStateException();
        }
    }

    @Override
    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }
}
